package com.zlht.controller;


import com.zlht.entity.Customer;
import com.zlht.entity.Store;
import com.zlht.service.CustomerService;
import com.zlht.service.imp.CustomerServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/customer")
public class CustomerServlet extends HttpServlet {

    CustomerService customerService = new CustomerServiceImp();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        switch (method) {
            case "list":
                req.setAttribute("list",this.customerService.list());
                req.getRequestDispatcher("customermanager.jsp").forward(req, resp);
                break;
            case "search":
                String key = req.getParameter("key");
                String value = req.getParameter("value");
                req.setAttribute("list",this.customerService.search(key ,value));
                req.getRequestDispatcher("customermanager.jsp").forward(req, resp);
                break;
            case "save":
                String name = req.getParameter("name");
                String gender = req.getParameter("gender");
                String age = req.getParameter("age");
                String phone = req.getParameter("phone");
                String email = req.getParameter("email");
                this.customerService.save(new Customer(name,gender,age,phone,email));
                resp.sendRedirect("/customer?method=list");
                break;
            case "update":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                name = req.getParameter("name");
                gender = req.getParameter("gender");
                age = req.getParameter("age");
                phone = req.getParameter("phone");
                email = req.getParameter("email");
                this.customerService.update(new Customer(id,name,gender,age,phone,email));
                resp.sendRedirect("/customer?method=list");
                break;
            case "delete":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                this.customerService.delete(id);
                resp.sendRedirect("/customer?method=list");
                break;
        }
    }
}
